package com.czh.intelligentoj.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czh.intelligentoj.common.ErrorCode;
import com.czh.intelligentoj.constant.CommonConstant;
import com.czh.intelligentoj.exception.BusinessException;
import com.czh.intelligentoj.judge.JudgeManager;
import com.czh.intelligentoj.judge.JudgeService;
import com.czh.intelligentoj.mapper.QuestionSubmitMapper;
import com.czh.intelligentoj.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.czh.intelligentoj.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.czh.intelligentoj.model.entity.Question;
import com.czh.intelligentoj.model.entity.QuestionSubmit;
import com.czh.intelligentoj.model.entity.User;
import com.czh.intelligentoj.model.enums.ProLanguageEnum;
import com.czh.intelligentoj.model.enums.QuestionSubmitStatusEnum;
import com.czh.intelligentoj.model.vo.QuestionSubmitVO;
import com.czh.intelligentoj.service.QuestionService;
import com.czh.intelligentoj.service.QuestionSubmitService;
import com.czh.intelligentoj.service.UserService;
import com.czh.intelligentoj.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/*
 * ClassName: QuestionSubmitImpl
 * Package: com.czh.intelligentoj.service.impl
 * Description:
 * @Author: CZH
 * @Create: 2024
 */
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit> implements QuestionSubmitService {
    @Resource
    private QuestionService questionService;
    @Resource
    private UserService userService;


    @Resource
    @Lazy
    private JudgeService judgeService;
    /**
     * 题目提交
     *
     * @param questionSubmitAddRequest
     * @param loginUser
     * @return
     */
    @Override
    public Long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        //校验编程语言是否合法
        String proLanguage = questionSubmitAddRequest.getProLanguage();
        ProLanguageEnum enumByValue = ProLanguageEnum.getEnumByValue(proLanguage);
        if (enumByValue == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编程语言不合法");
        }
        long questionId = questionSubmitAddRequest.getQuestionId();
        // 判断实体是否存在，根据id获取实体
        Question questionServiceId = questionService.getById(questionId);
        if (questionServiceId == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 是否已提交题目
        long userId = loginUser.getId();
        // 每个用户串行提交项目
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(userId);
        questionSubmit.setQuestionId(questionId);
        questionSubmit.setProLanguage(proLanguage);
        questionSubmit.setTitleCode(questionSubmitAddRequest.getTitleCode());
        questionSubmit.setTitleStatus(QuestionSubmitStatusEnum.WATTING.getValue());
        questionSubmit.setJudgeInfo("{}");
        boolean result = this.save(questionSubmit);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据插入失败");
        }
        long questionSubmitId = questionSubmit.getId();
        // 异步执行判题任务
        CompletableFuture.runAsync(() -> {
            // 异步执行判题
            judgeService.doJudge(questionSubmitId);
        });
        return questionSubmitId;
    }

    /**
     * 获取查询包装类
     *
     * @param questionSubmitQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }
        String proLanguage = questionSubmitQueryRequest.getProLanguage();
        Integer status = questionSubmitQueryRequest.getTitleStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();

        // 拼接查询条件
        queryWrapper.eq(StringUtils.isNotBlank(proLanguage), "proLanguage", proLanguage);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "user_id", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "question_id", questionId);
        queryWrapper.eq(QuestionSubmitStatusEnum.getEnumByValue(status) != null, "title_status", status);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),sortField);

        return queryWrapper;
    }
    /**
     *     对questionSubmit对象进行脱敏
     * @param questionSubmit
     * @param loginUser
     * @return
     *      题目VO对象
     */
    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit,User loginUser) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        // 判断是否为本人提交的题目，如果不是本人且不是管理员，则进行脱敏处理
        Long userId = loginUser.getId();
        //如果当前用户不是题目的提交者，或者不是管理员，进行具体代码信息进行判null处理
        if (userId != questionSubmit.getUserId() && !userService.isAdmin(loginUser)) {
            questionSubmitVO.setTitleCode(null);
        }
        return questionSubmitVO;
    }

    /**
     * 题目列表的分页查询
     * @param questionSubmitPage
     * @param loginUser
     * @return
     *        题目VO的分页对象
     */
    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {

        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollectionUtils.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream()
                .map(questionSubmit -> getQuestionSubmitVO(questionSubmit, loginUser))
                .collect(Collectors.toList());
        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }



}
